<template>
  <div class="question-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>试题列表</h1>
      <div class="actions">
        <el-button 
          v-if="hasPermission('question:category:create')"
          type="primary" 
          @click="handleAdd"
          icon="Plus"
        >
          新增试题
        </el-button>
        <el-button @click="handleImport" icon="Upload">
          导入试题
        </el-button>
        <el-button @click="handleExport" icon="Download">
          导出试题
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="queryParams.query" 
            placeholder="试题标题或内容" 
            clearable 
            @keyup.enter="handleSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="题型">
          <el-select 
            v-model="queryParams.type" 
            placeholder="全部类型" 
            clearable
            style="width: 150px"
          >
            <el-option 
              v-for="type in questionTypes" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select 
            v-model="queryParams.difficulty" 
            placeholder="全部难度" 
            clearable
            style="width: 120px"
          >
            <el-option 
              v-for="level in difficultyLevels" 
              :key="level.value" 
              :label="level.label" 
              :value="level.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学科">
          <el-select 
            v-model="queryParams.subjectId" 
            placeholder="全部学科" 
            clearable
            filterable
            style="width: 150px"
          >
            <el-option 
              v-for="subject in subjects" 
              :key="subject.id" 
              :label="subject.name" 
              :value="subject.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select 
            v-model="queryParams.categoryId" 
            placeholder="全部分类" 
            clearable
            filterable
            style="width: 150px"
          >
            <el-option 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="Search">
            搜索
          </el-button>
          <el-button @click="resetQuery" icon="Refresh">
            重置
          </el-button>
          <el-button type="success" @click="refreshData" icon="RefreshRight">
            刷新
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 试题列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>试题列表</span>
          <div class="header-actions">
            <el-tag type="info">共 {{ total }} 条记录</el-tag>
            <el-button-group>
              <el-button 
                :type="viewMode === 'table' ? 'primary' : ''" 
                @click="viewMode = 'table'"
                icon="List"
                size="small"
              >
                列表
              </el-button>
              <el-button 
                type="viewMode === 'card' ? 'primary' : ''" 
                @click="viewMode = 'card'"
                icon="Grid"
                size="small"
              >
                卡片
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'">
        <el-table 
          v-loading="loading" 
          :data="questions" 
          border 
          style="width: 100%"
          empty-text="暂无试题数据"
          row-key="id"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
          <el-table-column prop="type" label="类型" width="140" align="center">
            <template #default="scope">
              <el-tag :type="getQuestionTypeTagType(scope.row.type)">
                {{ scope.row.typeName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="180" align="center">
            <template #default="scope">
              <el-rate
                v-model="scope.row.difficulty"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}星"
              />
            </template>
          </el-table-column>
          <el-table-column prop="score" label="分值" width="80" align="center">
            <template #default="scope">
              <el-tag type="warning">{{ scope.row.score }}分</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="subjectName" label="学科" width="120" show-overflow-tooltip />
          <el-table-column prop="categoryName" label="分类" width="120" show-overflow-tooltip />
          <el-table-column prop="createdAt" label="创建时间" width="180" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewQuestion(scope.row)" icon="View" v-if="hasPermission('question:category:view')">
                查看
              </el-button>
              <el-button 
                v-if="hasPermission('question:category:update')"
                size="small" 
                type="primary" 
                @click="editQuestion(scope.row)" 
                icon="Edit"
              >
                编辑
              </el-button>
              <el-button 
                v-if="hasPermission('question:category:delete')"
                size="small" 
                type="danger" 
                @click="deleteQuestion(scope.row)" 
                icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <div v-loading="loading" class="question-cards">
          <div v-for="question in questions" :key="question.id" class="question-card">
            <el-card shadow="hover">
              <template #header>
                <div class="question-header">
                  <div class="question-title">{{ question.title }}</div>
                  <div class="question-meta">
                    <el-tag :type="getQuestionTypeTagType(question.type)" size="small">
                      {{ question.typeName }}
                    </el-tag>
                  </div>
                </div>
              </template>
              
              <div class="question-content">
                <div class="question-info">
                  <div class="info-item">
                    <span class="label">难度：</span>
                    <el-rate
                      v-model="question.difficulty"
                      disabled
                      size="small"
                    />
                  </div>
                  <div class="info-item">
                    <span class="label">分值：</span>
                    <el-tag type="warning" size="small">{{ question.score }}分</el-tag>
                  </div>
                  <div class="info-item">
                    <span class="label">学科：</span>
                    <span>{{ question.subjectName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">分类：</span>
                    <span>{{ question.categoryName || '-' }}</span>
                  </div>
                </div>
                
                <div class="question-actions">
                  <el-button type="primary" size="small" v-if="hasPermission('question:category:view')" @click="viewQuestion(question)" icon="View">
                    查看
                  </el-button>
                  <el-button 
                    v-if="hasPermission('question:category:update')"
                    size="small" 
                    type="primary" 
                    @click="editQuestion(question)" 
                    icon="Edit"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    v-if="hasPermission('question:category:delete')"
                    size="small" 
                    type="danger" 
                    @click="deleteQuestion(question)" 
                    icon="Delete"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        
        <div v-if="!loading && questions.length === 0" class="empty-state">
          <el-empty description="暂无试题数据" />
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 试题表单对话框 -->
    <QuestionFormDialog
      v-model="dialogVisible"
      :question="currentQuestion"
      :subjects="subjects"
      :categories="categories"
      @success="handleFormSuccess"
    />

    <!-- 试题详情对话框 -->
    <QuestionDetailDialog
      v-model="detailDialogVisible"
      :question="currentQuestion"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { questionApi } from '@/api/questions'
import { subjectApi } from '@/api/subjects'
import { questionCategoryApi } from '@/api/questionCategories'
import { usePermission } from '@/composables/usePermission'
import QuestionFormDialog from '@/components/questions/QuestionFormDialog.vue'
import QuestionDetailDialog from '@/components/questions/QuestionDetailDialog.vue'

const router = useRouter()
const { hasPermission } = usePermission()

// 问题类型选项
const questionTypes = [
  { value: 'SINGLE_CHOICE', label: '单选题' },
  { value: 'MULTIPLE_CHOICE', label: '多选题' },
  { value: 'TRUE_FALSE', label: '判断题' },
  { value: 'FILL_BLANK', label: '填空题' },
  { value: 'SHORT_ANSWER', label: '简答题' },
  { value: 'ESSAY', label: '问答题' }
]

// 难度等级选项
const difficultyLevels = [
  { value: 1, label: '简单' },
  { value: 2, label: '较简单' },
  { value: 3, label: '中等' },
  { value: 4, label: '较难' },
  { value: 5, label: '困难' }
]

// 状态变量
const loading = ref(false)
const questions = ref<any[]>([])
const subjects = ref<any[]>([])
const categories = ref<any[]>([])
const total = ref(0)
const viewMode = ref<'table' | 'card'>('table')
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentQuestion = ref<any>(null)

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 10,
  query: '',
  type: '',
  difficulty: undefined as number | undefined,
  subjectId: undefined as number | undefined,
  categoryId: undefined as number | undefined
})


// 获取问题类型标签颜色
const getQuestionTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'SINGLE_CHOICE': 'primary',
    'MULTIPLE_CHOICE': 'success',
    'TRUE_FALSE': 'warning',
    'FILL_BLANK': 'info',
    'ESSAY': 'danger'
  }
  return typeMap[type] || 'info'
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取学科列表
const fetchSubjects = async () => {
  try {
    const response = await subjectApi.getActiveSubjects()
    subjects.value = response.data || []
  } catch (error) {
    console.error('获取学科列表失败:', error)
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await questionCategoryApi.getActiveCategories(queryParams.subjectId)
    categories.value = response.data || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取试题列表
const fetchQuestions = async () => {
  loading.value = true
  try {
    const response = await questionApi.getQuestions({
      page: queryParams.page - 1,
      size: queryParams.size,
      query: queryParams.query || undefined,
      type: queryParams.type || undefined,
      difficulty: queryParams.difficulty,
      subjectId: queryParams.subjectId,
      categoryId: queryParams.categoryId
    })
    questions.value = response.data.content || []
    total.value = response.data.totalElements || 0
  } catch (error) {
    console.error('获取试题列表失败:', error)
    ElMessage.error('获取试题列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  queryParams.page = 1
  fetchQuestions()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.query = ''
  queryParams.type = ''
  queryParams.difficulty = undefined
  queryParams.subjectId = undefined
  queryParams.categoryId = undefined
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  fetchQuestions()
}

// 分页处理
const handleSizeChange = () => {
  queryParams.page = 1
  fetchQuestions()
}

const handleCurrentChange = () => {
  fetchQuestions()
}

// 试题操作
const handleAdd = () => {
  currentQuestion.value = null
  dialogVisible.value = true
}

const viewQuestion = (question: any) => {
  currentQuestion.value = question
  detailDialogVisible.value = true
}

const editQuestion = (question: any) => {
  currentQuestion.value = { ...question }
  dialogVisible.value = true
}

const deleteQuestion = async (question: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除试题"${question.title}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await questionApi.deleteQuestion(question.id)
    ElMessage.success('删除成功')
    fetchQuestions()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除试题失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 表单成功回调
const handleFormSuccess = () => {
  dialogVisible.value = false
  fetchQuestions()
}

// 导入导出
const handleImport = () => {
  router.push('/questions/import')
}

const handleExport = async () => {
  try {
    const response = await questionApi.exportQuestions(queryParams)
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `试题列表_${new Date().toISOString().slice(0, 10)}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 监听学科变化，重新获取分类
watch(() => queryParams.subjectId, (newVal) => {
  queryParams.categoryId = undefined
  if (newVal) {
    fetchCategories()
  } else {
    categories.value = []
  }
})

// 组件挂载
onMounted(async () => {
  await fetchSubjects()
  await fetchCategories()
  fetchQuestions()
})
</script>

<style scoped>
.question-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.actions {
  display: flex;
  gap: 12px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin: 0;
}

.table-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.card-view {
  min-height: 400px;
}

.question-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.question-card {
  height: 100%;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
}

.question-title {
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
  flex: 1;
}

.question-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.question-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  color: #909399;
  font-size: 14px;
  min-width: 50px;
}

.question-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-card__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card) {
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
}
</style>


